from sqlalchemy import and_, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload

from app.database.models import Order, User


async def get_user_subscription_order(
    session: AsyncSession, user_id: int, joined: bool = True
) -> Order:

    q = (
        select(Order)
        .outerjoin(Order.user)
        .filter(
            and_(
                User.telegram_id == user_id,
                Order.type == "subscription",
                Order.status == "active",
            )
        )
    )

    if joined:
        q = q.options(
            joinedload(Order.proxies),
            joinedload(Order.category),
            joinedload(Order.site),
            joinedload(Order.provider),
            joinedload(Order.country),
            joinedload(Order.user),
            joinedload(Order.allowed_ips),
        )

    res = await session.execute(q)

    return res.scalar()
